package com.aabbc.database.aop;

import com.aabbc.database.bean.MultiDBContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * DataSourceAop
 *
 * @author: chenfenghai
 * @version: 1.0
 * @date: 2020-04-02 11:01
 * @blame Team
 */
@Aspect
@Component
public class DataSourceAop {

    @Pointcut("@annotation(com.aabbc.database.annotation.Slave)")
    public void readPointcut() {

    }

    @Pointcut("@annotation(com.aabbc.database.annotation.Master)")
    public void writePointcut() {

    }

    @Before("readPointcut()")
    public void read() {
        MultiDBContextHolder.slave();
    }

    @Before("writePointcut()")
    public void write() {
        MultiDBContextHolder.master();
    }

    private static final String[] SLAVE_METHOD_PREFIX_ARRAY = new String[]{
            "get", "select", "find", "query", "list", "page", "count"};

    /**
     * 另一种写法：if...else...  判断哪些需要读从数据库，其余的走主数据库
     */
    @Before("within(com.baomidou.mybatisplus.extension.service.IService+)")
    public void before(JoinPoint jp) {
        String methodName = jp.getSignature().getName();
        System.out.println("JoinPoint----------->" + methodName);
        if (StringUtils.startsWithAny(methodName, SLAVE_METHOD_PREFIX_ARRAY)) {
            MultiDBContextHolder.slave();
        }else {
            MultiDBContextHolder.master();
        }
    }
}
